package com.ly.blog_article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.blog_article.dao.CategoryDao;
import com.ly.blog_article.entity.CategoryEntity;
import com.ly.blog_article.service.CategoryService;
import com.ly.blog_common.utils.PageUtils;
import com.ly.blog_common.utils.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public List<CategoryEntity> listWithTree() {

        //1、查询分类数据
        List<CategoryEntity> categoryEntities= baseMapper.selectList(null);

        //2、组装父子结构
        //找到一级分类
        List<CategoryEntity> categoryTreeList = new ArrayList<>();
        //从 -1 默认父节点到现在的 1 分类节点
        categoryTreeList = getChildren(1,categoryEntities);

        return categoryTreeList;
    }

    //获取到当前节点下属节点信息
    private List<CategoryEntity> getChildren(long categoryEntityId, List<CategoryEntity> categoryEntityAll) {
        return categoryEntityAll.stream()
                .filter(categoryEntityTemp -> categoryEntityId == categoryEntityTemp.getParentId()) //过滤数据
                .map(categoryEntity1 -> { //当前节点下属节点信息
                    categoryEntity1.setChildren(getChildren(categoryEntity1.getId(),categoryEntityAll));
                    return categoryEntity1;
                })
                .sorted((c1,c2) -> c1.getSort() - c2.getSort()) //排序
                .collect(Collectors.toList());
    }

}